<template>
  <div class="app-container" ref="appContainer">
    <div class="header">
      <el-form :inline="true" class="search-form" :model="inputSearch" ref="ruleFormRef">
        <el-form-item label="请输入用户ID">
          <el-input v-model="inputSearch.searchId" :placeholder="`请输入用户ID`" clearable />
        </el-form-item>
      </el-form>
      <div class="search">
        <el-button type="primary" @click="onclickSearch" :icon="Search">搜索</el-button>
      </div>
    </div>

    <!-- ------------表格--------------->
    <div class="table">
      <el-table v-loading="loading" :data="list" fit highlight-current-row style="width: 100%" :border="true">
        <el-table-column label="用户ID" align="center" prop="userid" width="125px">
        </el-table-column>
        <el-table-column label="账号" align="center" prop="account" width="350px">
        </el-table-column>

        <el-table-column label="头像" width="90px" align="center">
          <template #default="scope">
            <el-avatar :size="80" :src="scope.row.headimg">
              <img src="@/assets/image/userlogo.png" />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="呢称" align="center" prop="nick_name" width="125px">
        </el-table-column>
        <el-table-column label="形象照" width="90px" align="center">
          <template #default="scope">
            <el-avatar :size="80" shape="square" :src="scope.row.img1">
              <img src="@/assets/image/userlogo.png" />
            </el-avatar>

          </template>
        </el-table-column>
        <el-table-column label="上传形象照" width="100px">
          <template #default="scope">
            <el-upload class="upload-demo" :action="getUploadUrl(scope.row)" :on-preview="handlePreview"
              :on-remove="handleRemove" :file-list="fileList" list-type="picture" :limit=1
              :before-upload="beforeAvatarUpload" :on-success="getList" >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </template>

          <!-- <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload> -->
        </el-table-column>
        <el-table-column label="推广员" align="center" prop="lv_str" width="100px">
        </el-table-column>
        <el-table-column label="渠道代理" align="center" prop="qudaodaili_str" width="100px">
        </el-table-column>
        <el-table-column label="钻石" align="center" prop="gems" width="100px">
        </el-table-column>
        <el-table-column label="金豆" align="center" prop="coins" width="100px">
        </el-table-column>
        <el-table-column label="推广金豆" align="center" prop="income" width="100px">
        </el-table-column>
        <el-table-column label="魅力值" align="center" prop="meilis" width="100px">
        </el-table-column>
        <el-table-column label="状态" align="center" prop="state_str" width="100px">
        </el-table-column>

        <el-table-column label="操作" align="center" width="300px">
          <template #default="scope">
            <el-button type="success" @click="onClickCharge(scope.row)">充值</el-button>
            <el-button type="success" @click="onClickUnBind(scope.row)">解绑</el-button>
            <el-button type="warning" @click="onClickFengJin(scope.row)">{{ get_fengjin_word(scope.row) }}</el-button>
            <el-button type="primary" @click="onClickNormalDaili(scope.row)">{{ get_normaldaili_word(scope.row)
            }}</el-button>
            <el-button type="danger" @click="onClickQudaodaili(scope.row)">{{ get_qudaodaili_word(scope.row)
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- ------------分页--------------->
    <!-- <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pagenum" :limit.sync="listQuery.pagesize"
      @pagination="getList" /> -->

    <!-- ------------分页--------------->
    <div class="pagination">
      <el-pagination v-model:currentPage="listQuery.pagenum" :page-size="listQuery.pagesize" background
        layout="total, sizes, prev, pager, next, jumper" :total="pageObj.total" @size-change="handleSizeChange"
        @current-change="getList" />
    </div>


    <el-dialog v-model="dialogVisible" title="玩家充值" width="80%">
      <el-form :model="chargeForm">
        <el-form-item label="玩家昵称">
          <el-input :value="chargeForm.name" disabled />
        </el-form-item>
        <el-form-item label="玩家ID">
          <el-input :value="chargeForm.userid" disabled />
        </el-form-item>
        <el-form-item label="当前钻石">
          <el-input :value="chargeForm.gems" disabled />
        </el-form-item>
        <el-form-item label="当前金豆">
          <el-input :value="chargeForm.coins" disabled />
        </el-form-item>
        <el-form-item label="推广未兑换金豆">
          <el-input :value="chargeForm.income" disabled />
        </el-form-item>
        <el-form-item label="当前魅力">
          <el-input :value="chargeForm.meilis" disabled />
        </el-form-item>


        <el-form-item label="选择充值类型">
          <el-radio-group v-model="chargeForm.type">
            <el-radio label="gems">钻石</el-radio>
            <el-radio label="coins">金豆</el-radio>
            <el-radio label="meilis">魅力</el-radio>
            <el-radio label="income">未兑换金豆</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="输入充值数量(负数表示扣除)">
          <el-input v-model="chargeForm.num" type="number" clearable />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRechargeSubmit()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>
<script lang="ts" setup name="comprehensive">
import { Search } from '@element-plus/icons-vue'
import { computed, ref, reactive, onMounted, nextTick } from 'vue'
import * as dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Logger } from '@/engine/util/Logger'
import { HttpClient } from '@/utils/HttpClient'
import { da, fa, fi, ro, tr } from 'element-plus/es/locale'
import { UIHelper } from '@/utils/UIHelper'
import { Config } from '@/config/Config'
import { config } from 'exceljs'
import { UserModel } from '@/store/model/UserModel'
const loading = ref(true)
const appContainer = ref(null)

let uploadUrl = Config.getUploadImgUrl()
const imageUrl = ref("")

let fileList = []

const inputSearch = reactive({
  searchId: '',
})

//列表查询选项
const listQuery = reactive({
  pagenum: 1, //第几页
  pagesize: 10, //一页多少个
})

let list = reactive([
  {
    "userid": 1,
    "coins": 0,
    "gems": 0,
    "meilis": 0,
    "income": 0,
  }
])
let pageObj = reactive({
  total: 0
})

const dialogVisible = ref(false)
const chargeForm = reactive({
  name: '',
  userid: 111,
  gems: 0,
  coins: 0,
  income: 0,
  meilis: 0,
  type: "gems",
  num: "0"
})



onMounted(() => {
  nextTick(() => {
    // let data = appContainer.value.
  })
  setTimeout(() => {
    loading.value = false
  }, 500)
  getList()
})


const onclickSearch = () => {
  Logger.log('onclickSearch!', inputSearch)
  // if(inputSearch.searchId ==)
  let searchId: number = parseInt(inputSearch.searchId)
  if (isNaN(searchId)) {
    // UIHelper.showMsg("请输入正常的用户id")
    getList()
  } else {
    HttpClient.get_user_info(searchId, (data: object) => {
      formatUserList(data["users"])
    })
  }
}

const handleSizeChange = (val: number) => {
  listQuery.pagesize = val
  getList()
}

const formatUserList = (users: Array<object>) => {
  list.splice(0)
  for (let i = 0; i < users.length; i++) {
    let user = {
      "userid": users[i]["userid"],
      "account": users[i]["account"],
      "headimg": users[i]["headimg"],
      "nick_name": users[i]["nick_name"],
      "img1": users[i]["img1"],
      "invite": users[i]["invite"],
      "lv": users[i]["lv"],
      "lv_str": users[i]["lv"] ? "是" : "否",
      "qudaodaili": users[i]["qudaodaili"],
      "qudaodaili_str": users[i]["qudaodaili"] ? "是" : "否",
      "gems": users[i]["gems"],
      "coins": users[i]["coins"],
      "income": users[i]["income"] || 0,
      "meilis": users[i]["meilis"] || 0,
      "state": users[i]["state"]
    }
    if (users[i]["state"] == 1) {
      user["state_str"] = "正常"
    }
    else if (users[i]["state"] == 0) {
      user["state_str"] = "封禁"
    }
    else if (users[i]["state"] == 0) {
      user["state_str"] = "测试账号"
    }
    list[i] = user
  }
}

const getList = () => {
  loading.value = true;
  HttpClient.get_user_list(listQuery.pagenum, listQuery.pagesize, (data: object) => {
    loading.value = false
    let users: Array<object> = data["users"]
    formatUserList(users)
    pageObj.total = data["count"]
    Logger.log("list", list)
    Logger.log("total", pageObj)
  })
}

const onClickUnBind = (row) => {
  Logger.log("onClickUnBind", row)
  HttpClient.unbind(row["userid"], () => {
    getList()
  })
}

const onClickCharge = (row) => {
  Logger.log("onClickCharge", row)
  chargeForm.coins = row.coins
  chargeForm.gems = row.gems
  chargeForm.income = row.income
  chargeForm.meilis = row.meilis
  chargeForm.name = row.nick_name
  chargeForm.userid = row.userid
  chargeForm.num = "0"
  chargeForm.type = "gems"
  dialogVisible.value = true
}

const handleRechargeSubmit = () => {
  Logger.log("handleRechargeSubmit=", chargeForm)
  let num: number = parseInt(chargeForm.num)
  if (isNaN(num)) {
    UIHelper.showMsg("请输入正确的充值数额")
  } else {
    dialogVisible.value = false
    HttpClient.charge_by_gm(chargeForm.userid, num, chargeForm.type, () => {
      // onclickSearch()
      for (let i = 0; i < list.length; i++) {
        if (list[i].userid == chargeForm.userid) {
          if (chargeForm.type == "coins") {
            list[i].coins += num
          }
          else if (chargeForm.type == "gems") {
            list[i].gems += num
          }
          else if (chargeForm.type == "meilis") {
            list[i].meilis += num
          }
          else if (chargeForm.type == "income") {
            list[i].income += num
          }
        }
      }
    })
  }
}

const get_fengjin_word = (row) => {
  if (row.state == 0) {
    return "解封"
  }
  else {
    return "封禁"
  }
}

const get_normaldaili_word = (row) => {
  // Logger.log("get_normaldaili_word=", row.lv)
  if (row.lv > 0) {
    return "取消普通代理(VIP)"
  }
  else {
    return "设为普通代理(VIP)"
  }
}

const get_qudaodaili_word = (row) => {
  // Logger.log("get_normaldaili_word=", row.qudaodaili)
  if (row.qudaodaili > 0) {
    return "取消渠道代理"
  }
  else {
    return "设为渠道代理"
  }

}

const onClickNormalDaili = (row) => {
  let userid: number = row.userid
  let lv: number = row.lv
  if (lv == 0) {
    lv = 1;
  }
  else {
    lv = 0
  }
  HttpClient.set_normal_daili(userid, lv, () => {
    row.lv = lv
  })
}

const onClickQudaodaili = (row) => {
  let userid: number = row.userid
  let qudaodaili: number = row.qudaodaili
  if (qudaodaili == 0) {
    qudaodaili = 1;
  }
  else {
    qudaodaili = 0
  }
  HttpClient.set_qudao_daili(userid, qudaodaili, () => {
    row.qudaodaili = qudaodaili
  })

}

const onClickFengJin = (row) => {
  let userid: number = row.userid
  let needState: number = 0
  if (row.state == 0) {
    needState = 1;
  }
  else {
    needState = 0
  }
  HttpClient.fengjin_user(userid, needState, () => {
    row.state = needState;
    if (row.state == 1) {
      row.state_str = "正常"
    }
    else if (row.state == 0) {
      row.state_str = "封禁"
    }
  })
}

const beforeAvatarUpload = (file) => {
  // Logger.log("beforeAvatarUpload==", file)
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 15;

  // if (!isJPG) {
  //   this.$message.error('上传头像图片只能是 JPG 格式!');
  // }
  // if (!isLt2M) {
  //   this.$message.error('上传头像图片大小不能超过 2MB!');
  // }
  return isJPG && isLt2M;
}

const getUploadUrl = (row) => {
  // Logger.log("getUploadUrl==", row)
  let url: string = Config.getUploadImgUrl() + "?userid=" + row["userid"] + "&uploadType=2&token=" + UserModel.instance.token
  return url
}

const handleAvatarSuccess = (res, file) => {
  imageUrl.value = URL.createObjectURL(file.raw);
  Logger.log("handleAvatarSuccess==", imageUrl.value)
}

const handlePreview = (file) => {
  Logger.log("handlePreview", file);
}

const handleRemove = (file, fileList) => {
  Logger.log("handleRemove", file, fileList);
}

// const getSummaries = (param) => {
//   // const { columns, data } = param;
//   const sums = [];
//   sums[0] = "合计";
//   let sum_chargePeople: number = 0;
//   let sum_chargeMoney: number = 0;
//   // for (let i = 0; i < this.showList.length; i++) {
//   //   let model: ChargeModel = this.showList[i];
//   //   sum_chargePeople += model.chargePeople;
//   //   sum_chargeMoney += model.chargeMoney;
//   // }
//   sums[1] = sum_chargePeople;
//   sums[2] = sum_chargeMoney;
//   return sums;
// }
</script>
  
<style scoped lang="scss">
.header {
  display: flex;
  padding: 16px 16px 0 16px;
  margin-bottom: 16px;
  border-radius: 4px;
  background: white;
  box-shadow: 0 0 12px rgb(0 0 0 / 5%);

  .search-form {
    flex: 1;

    ::v-deep {
      .el-input--default {
        width: 200px;
      }
    }
  }

  .search {
    flex-shrink: 0;
    white-space: nowrap;
  }
}
</style>
  